package leo.gptBot.gpt.tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author ：Leo
 * @date ：Created in 2024/7/31 14:42
 * @description：操作邮箱工具
 */
@Component
@Slf4j
public class MailTool {
    private static String username;
    private static String password;
    public MailTool(@Value("${mail.username}") String username, @Value("${mail.password}") String password) {
        MailTool.username = username;
        MailTool.password = password;
    }

    public static Session createSession(){
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.163.com");
        properties.put("mail.smtp.port", "25");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        return Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    }
    @Tool("This tool can help you send an email.")
    public String sendMail(@P("Recipient email") String to, @P("Email Subject") String subject, @P("content of email") String content) {
        log.info("调用send email工具");
        Session session = createSession();
        try {
            MimeMessage message = new MimeMessage(session);
            message.setSubject(subject);
            message.setText(content);
            message.setFrom(new InternetAddress(username));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            Transport.send(message);
        } catch(Exception e) {
            return "邮件发送失败!";
        }
        return "邮件发送成功!";
    }

}
